package com.zll.service.impl;

import com.zll.Store;
import com.zll.domain.Product;
import com.zll.dto.ProductDto;
import com.zll.feign.StoreService;
import com.zll.mapper.ProductMapper;
import com.zll.service.ProductService;
import com.zll.utils.JsonResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class ProductServiceImpl implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private StoreService storeService;

    @Override
    @Transactional
    public JsonResult add(ProductDto productDto) {
        try {
            // 1.把商品信息保存到数据库
            Product product = new Product();
            product.setName(productDto.getName());
            product.setPrice(productDto.getPrice());
            productMapper.add(product); //开启返回主键到id字段

            // 2.把库存保存到数据库，调用feign接口
            Store store = new Store();
            store.setProductId(product.getId());
            store.setNumber(productDto.getNumber());
            JsonResult add = storeService.add(store);
            if (!add.getSuccess()) {
                return add;
            }
            return new JsonResult();
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new JsonResult(false,"操作失败，请稍后重试");
        }
    }
}
